package com.sikadwafastdaisfondturbo.pretloan.ui.launch

import android.os.Bundle
import android.view.View
import com.sikadwa.lib_permission.XXPermissions
import com.sikadwafastdaisfondturbo.pretloan.R
import com.sikadwafastdaisfondturbo.pretloan.analysis.TestAnalysisInit
import com.sikadwafastdaisfondturbo.pretloan.analysis.TestDataLibInit
import com.sikadwafastdaisfondturbo.pretloan.databinding.ActivityLaunchBinding
import com.sikadwafastdaisfondturbo.pretloan.pro.ProActivity
import com.sikadwafastdaisfondturbo.pretloan.ui.credit.activity.CreditActivity
import com.sikadwafastdaisfondturbo.pretloan.ui.permission.PermissionActivity
import com.sikadwafastdaisfondturbo.pretloan.ui.user.activity.UserLoginActivity
import com.sikadwafastdaisfondturbo.pretloan.utils.config.Configs
import com.sikadwafastdaisfondturbo.pretloan.utils.event.EventType
import com.sikadwafastdaisfondturbo.pretloan.utils.helper.ActivityStackHelper
import com.sikadwafastdaisfondturbo.pretloan.utils.http.AppUrls
import com.sikadwafastdaisfondturbo.pretloan.utils.http.IHttpCallback
import org.json.JSONObject
import java.util.TimeZone

/**
 * Sikadwa
 * @Author wwdeng
 * @CreateTime: 2024/5/21 16:12
 * @Annotation：启动页
 */
class LaunchActivity : ProActivity() {

    private lateinit var binding: ActivityLaunchBinding

    override fun getRootView(): View {
        binding = ActivityLaunchBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initView() {
        isNeedHideLoading = false
        //关闭所有页面
        ActivityStackHelper.finishAllActivity(LaunchActivity::class.java)
    }

    override fun initListener() {

    }

    override fun initData() {
        showLoading()
        loadTimeZoneAction()
    }

    /**
     * 进入权限申请
     */
    fun enterPermissionPage(permissings: String) {
        val bundle = Bundle()
        bundle.putString("Permissings",permissings)
        onIntent(PermissionActivity::class.java,bundle)
        finish()
    }

    /**
     * 进入登录
     */
    fun enterLoginPage() {
        onIntent(UserLoginActivity::class.java)
        finish()
    }

    /**
     * 进入主页
     */
    fun enterMainPage() {
        onIntent(CreditActivity::class.java)
        finish()
    }

    override fun onStart() {
        super.onStart()
        addEvent(EventType.PAGE.PAGE_LAUNCH_START,"")
    }

    override fun onDestroy() {
        super.onDestroy()
        addEvent(EventType.PAGE.PAGE_LAUNCH_END,"")
    }

    /**
     * 获取地区转发
     * Timezone
     */
    private fun loadTimeZoneAction(){
        val params = JSONObject().apply {
            put("p",getString(R.string.app_name).uppercase())
            put("tz", TimeZone.getDefault().id)
        }
        val httpUrl = AppUrls.APP_URL + AppUrls.URL.TIMEZONE
        postAction(httpUrl,params,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                val dataString = data.optString("data")
                val timeZone = dataString.split(",")[0]
                val zoneCode = dataString.split(",")[1]
                //保存转发地区
                Configs.saveSPString(Configs.SPKEY.SIKADWA_TIMEZONE,timeZone)
                //保存转发地区 区号
                Configs.saveSPString(Configs.SPKEY.SIKADWA_TIMEZONE_CODE,zoneCode)
                //初始化analysis lib 赋值 转发地区
                TestAnalysisInit.initAnalysisLibAtZoneSuccess()
                //初始化 data lib
                TestDataLibInit.initDataLibAtZoneSuccess()
                //添加埋点
                addEvent(EventType.PAGE.PAGE_LAUNCH_START,"")
                loadConfigAction()
            }

            override fun onRequestError(error: JSONObject) {
            }

            override fun onRequestFinish() {
            }

        })
    }

    /**
     * 获取APP配置信息
     */
    private fun loadConfigAction(){
        val params = JSONObject().apply {
            put("product",Configs.AppName)
            put("path",AppUrls.PATH.APP_INFO)
        }
        val httpUrl = AppUrls.getHttpUrl(AppUrls.URL.COMMON)
        postAction(httpUrl,params,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                val obj = data.optJSONObject("obj")
                //保存所有数据
                if (obj != null) {
                    Configs.saveSPString(Configs.SPKEY.SIKADWA_COMMON,obj.toString())
                }

                val customizeObj = obj?.optJSONObject("customize")
                val permissionsObj = customizeObj?.optJSONObject("permissions")
                val permissionArray = permissionsObj?.optJSONArray("permission")
//                val home = permissionsObj?.optJSONArray("home")
//                home!!.put("android.permission.CAMERA")
                if (permissionArray != null) {
                    if (permissionArray.length() > 0){
                        //是否全部申请
                        var isAll = true
                        for (i in 0..<permissionArray.length()){
                            val permission = permissionArray.optString(i)
                            //存在未授权的权限
                            if (!XXPermissions.isGranted(getContext()!!, permission)){
                                isAll = false
                                break
                            }
                        }
                        if (isAll){//已全部授权

                            //已登录 - 进入主页
                            if (Configs.getSPBoolean(Configs.SPKEY.SIKADWA_LOGIN)){
                                //初始化analysis lib 赋值 用户id 和 token
                                TestAnalysisInit.initAnalysisLibAtLoginSuccess()
                                enterMainPage()
                            } else {//进入登录页
                                enterLoginPage()
                            }

                        } else {
                            //进入权限页
                            enterPermissionPage(permissionArray.toString())
                        }
                    } else {
                        //进入登录
                        enterLoginPage()
                    }
                }
            }

            override fun onRequestError(error: JSONObject) {
            }

            override fun onRequestFinish() {
                hideLoading()
            }
        })
    }
}